import winreg
import os
import sys
import json
import shutil
import ctypes
import random

def check_admin():
    try:
        return os.getuid() == 0
    except AttributeError:
        import ctypes
        return ctypes.windll.shell32.IsUserAnAdmin() != 0


def create_default_dlist(file_path, default_data):
    #创建默认名单文件
    try:
        dir_path = os.path.dirname(file_path)
        if not os.path.exists(dir_path):
            os.makedirs(dir_path, exist_ok=True)
        if not os.path.exists(file_path):
            with open(file_path, 'w', encoding='utf-8') as f:
                json.dump(default_data, f, ensure_ascii=False)
            print(f'已创建默认文件: {file_path}')
        else:
            print(f'文件已存在: {file_path}')
            return False
    except Exception as e:
        print(f'创建默认文件失败: {str(e)}')
        sys.exit(1)

def register_file_association():
    if not check_admin():
        print('不是管理员')
        sys.exit(1)

    ext = '.dlist'
    exe_path = r'D:\Jappstudio\dmzs\zsmain.exe'
    ico_path = os.path.join(os.path.dirname(__file__), 'zsicon.ico')

    try:
        with winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, ext, 0, winreg.KEY_READ) as key:
            current_handler = winreg.QueryValue(key, None)
            if current_handler == 'dlist_auto_file':
                with winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, current_handler) as handler_key:
                    command = winreg.QueryValue(handler_key, r'shell\open\command')
                    if exe_path in command:
                        print('文件关联已设置')
    except FileNotFoundError:
        pass

    try:
        # 创建/更新文件类型关联
        with winreg.CreateKey(winreg.HKEY_CLASSES_ROOT, ext) as key:
            winreg.SetValue(key, None, winreg.REG_SZ, 'dlist_auto_file')

        with winreg.CreateKey(winreg.HKEY_CLASSES_ROOT, 'dlist_auto_file') as key:
            winreg.SetValue(key, None, winreg.REG_SZ, '点名名单文件')
            winreg.SetValueEx(key, 'FriendlyTypeName', 0, winreg.REG_SZ, '点名名单文件')
            
            with winreg.CreateKey(key, 'DefaultIcon') as icon_key:
                winreg.SetValue(icon_key, None, winreg.REG_SZ, ico_path)
            
            with winreg.CreateKey(key, r'shell\open\command') as cmd_key:
                winreg.SetValue(cmd_key, None, winreg.REG_SZ, f'"{exe_path}" "%1"')

        print('文件关联设置成功')
        
        # 创建默认文件
        DEFAULT_PATH = r'D:\\Jappstudio\\dmzs\\default.dlist'
        if create_default_dlist(DEFAULT_PATH, ["张三","李四","王五","测试","三个字","大香蕉"]) is not False:
            import ctypes
            ctypes.windll.user32.MessageBoxW(0, "首次启动需重启软件", "提示", 0x40)
            sys.exit(0)
        
        # 读取默认名单文件
        global md
        try:
            with open(DEFAULT_PATH, 'r', encoding='utf-8') as f:
                md = json.load(f)
            print('默认名单加载成功')
        except FileNotFoundError:
            print(f'未找到默认名单文件: {DEFAULT_PATH}')
            sys.exit(1)
        except json.JSONDecodeError:
            print('名单文件格式错误')
            sys.exit(1)
    except Exception as e:
        print(f'注册表操作失败: {str(e)}')
        sys.exit(1)

def handle_file_association(file_path):
    if not check_admin():
        print('不是管理员')
        sys.exit(1)

    res = ctypes.windll.user32.MessageBoxW(0, 
        "是否导入并覆盖名单数据（旧的名单将被删除）？",
        "警告",
        0x34)

    if res == 6:  # IDYES
        global DEFAULT_PATH
        try:
            if os.path.exists(DEFAULT_PATH):
                os.remove(DEFAULT_PATH)
            shutil.copy(file_path, DEFAULT_PATH)
            print('名单数据已覆盖')
        except Exception as e:
            print(f'文件操作失败: {str(e)}')
            sys.exit(1)
    sys.exit(0)

def gui_display():
    import tkinter as tk
    from ctypes import windll
    
    # 设置DPI感知
    windll.shcore.SetProcessDpiAwareness(1)
    
    root = tk.Tk()
    root.title('抽签助手')
    root.geometry('900x700')
    root.resizable(False, False)
    
    # 主容器使用Frame实现居中布局
    main_frame = tk.Frame(root)
    main_frame.pack(expand=True, fill='both')
    
    # 上部文本标签
    lbl = tk.Label(main_frame, 
                  text='请抽选',
                  font=('Microsoft YaHei', 100),
                  fg='#FF69B4',
                  anchor='center')
    
    lbl.pack(expand=True)
    
    # 创建按钮容器
    btn_frame = tk.Frame(main_frame)
    btn_frame.pack(side='bottom', pady=20)
    
    # 抽签按钮
    def on_draw_click():
        lbl.config(text='抽签中...')
        result = dm(len(md))
        lbl.config(text=result)

    draw_btn = tk.Button(btn_frame,
                        text='抽签',
                        font=('Microsoft YaHei', 24),
                        width=8,
                        height=1,
                        command=on_draw_click)
    draw_btn.pack()
    
    root.mainloop()

def dm(num):
    dmd = ''
    d1list = []
    for i in range(5):
        d1 = random.randint(1, num)
        d1list.append(d1)
    print(d1list)
    d2list = []
    for i in range(3):
        d2 = d1list[(random.randint(1, 5) - 1)]
        d2list.append(d2)
    print(d2list)
    d3 = random.randint(1, 3)
    d3 = d2list[(d3 - 1)]
    print(d3)
    dmd = md[(d3 - 1)]
    print(dmd)
    return dmd

if __name__ == '__main__':
    if len(sys.argv) > 1:
        if sys.argv[1].endswith('.dlist') and os.path.exists(sys.argv[1]):
            handle_file_association(sys.argv[1])
    register_file_association()
    gui_display()